package com.monkey.web.platform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.monkey.core.domain.code.CodeTemplate;
import com.monkey.core.exception.MonkeyException;
import com.monkey.core.plugin.code.tpl.CodeTemplateGenerator;
import com.monkey.core.plugin.dto.MonkeyDto;
import com.monkey.core.service.BaseServiceImpl;
import com.monkey.web.context.Global;
import com.monkey.web.platform.service.CodeTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * Project  : monkey
 * Author   : Wu Tian Qiang
 * Date     : 2016/9/12
 */
@Service
public class CodeTemplateServiceImpl extends BaseServiceImpl<CodeTemplate, Long> implements CodeTemplateService {

    @Override
    public void addTemplate(MonkeyDto monkeyDto) {
        CodeTemplate codeTemplate = CodeTemplate.createFromMonkeyDto(monkeyDto);
        save(codeTemplate);
    }

    @Override
    public void modifyTemplate(MonkeyDto monkeyDto) {
        Long id = monkeyDto.getLong("id");
        CodeTemplate template = findOne(id);
        CodeTemplate.modifyFromMonkeyDto(template, monkeyDto);
        update(template);
    }

    @Override
    public void startGenerate(MonkeyDto monkeyDto) {
        monkeyDto.put("projectPath", Global.getProjectPath());
        monkeyDto.put("codeGenerator", Global.getConfig("code.generator"));
        monkeyDto.put("entityIdType", Global.getConfig("entity.id.type"));
        JSONObject template = JSON.parseObject(monkeyDto.getString("template"));
        String className = template.getString("packagePath") + "." + template.getString("className");
        try {
            Class<?> clazz = Class.forName(className);
            CodeTemplateGenerator generator = (CodeTemplateGenerator) BeanUtils.instantiate(clazz);
            generator.generate(monkeyDto);
        } catch (ClassNotFoundException e) {
            throw new MonkeyException("不能够找到生成模版的类");
        }
    }

}
